package com.jxs.android.sxyw;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jxs.android.http.CustomMultipartEntity;
import com.jxs.android.http.CustomMultipartEntity.ProgressListener;
import com.jxs.android.sxyw.weiget.BuProgress;
import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.FileHloder;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StatusHelper;
import com.jxs.android.util.StringUtils;

/**
 * @Des 上传图片
 * @author Jiangxs
 * 
 */
public class UploadPic extends AbstractActivity {

	private ListView uploadListView = null;

	private final int UPDATE_PROGRESS = 0x1025;
	private final int DOWNLOAD_COMPLETE = 0x1026;
	private static final int TO_LOGIN = 0x1019;
	private String ticket = "";

	private Context context;
	private List<UpdateFileInfo> uploadFileInfos = new ArrayList<UpdateFileInfo>();
	private ArrayList<String> fileNames = new ArrayList<String>();
	private PicAdpter picAdpter;
	private String danger_id;
	private String upload_url;
	long lastUpdatedTime = 0;
	private static final int UPDATE_GAP = 1000;// 1 second

	@Override
	public void initTopBar(Bundle savedInstanceState, int layoutId) {
		if (!StatusHelper.isNetworkAvailable(this)) {
			StatusHelper.checkNetworkAvailable(this);
		}
		super.onCreate(savedInstanceState);
		setContentView(layoutId);
		TopBar topBar = (TopBar) findViewById(R.id.topBar);
		if (null != topBar) {
			topBarLogic(topBar);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.common_with_list);

		context = this;
		uploadListView = (ListView) findViewById(R.id.common_listview);

		if (null != getIntent()) {
			if (null != getIntent().getExtras()) {
				Bundle bundle = getIntent().getExtras();
				danger_id = bundle.getString("danger_id");
				ticket = bundle.getString("ticket");
				upload_url = bundle.getString("upload_url");
				ArrayList<String> reciveredFileNames = bundle.getStringArrayList("fileNames");
				for (int index = 0; index < reciveredFileNames.size(); index++) {
					if (!StringUtils.isEmpety(reciveredFileNames.get(index))) {
						File file = new File(FileHloder.DIR_PIC + reciveredFileNames.get(index));
						if (file.exists() && file.isFile()) {
							UpdateFileInfo fileInfo = new UpdateFileInfo(FileHloder.getLocationBitmap(FileHloder.DIR_PIC + reciveredFileNames.get(index)), FileHloder.getFormatFileSize(new File(FileHloder.DIR_PIC + reciveredFileNames.get(index))));
							uploadFileInfos.add(fileInfo);
							fileNames.add(index, reciveredFileNames.get(index));
						}
					}
				}
			}
		}
		picAdpter = new PicAdpter(context);
		uploadListView.setAdapter(picAdpter);

		new HttpMultipartPost().execute(0);

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_PROGRESS) {
				// 视野内的文件 的进度发生改时才会刷新，并且刷新间隔不大于UPDATE_GAP
				// 当ListView中的按钮被按下时刷新界面会出新一些问题，比如按下了第2个按钮，当界面刷新的时候有可能
				// 显示第4个按钮被按下了，所以先作个检查，当有ListView当中的按钮被按下时，不进行刷新
				if (msg.arg1 >= uploadListView.getFirstVisiblePosition() && msg.arg1 <= uploadListView.getFirstVisiblePosition() + uploadListView.getChildCount() && System.currentTimeMillis() - lastUpdatedTime > UPDATE_GAP) {
					picAdpter.notifyDataSetChanged();
					lastUpdatedTime = System.currentTimeMillis();
				}
			} else if (msg.what == DOWNLOAD_COMPLETE) {
				int postion = msg.arg1 + 1;
				if (postion >= uploadFileInfos.size()) {
					setResult(RESULT_OK);
					finish();
				} else {
					new HttpMultipartPost().execute(postion);
				}

			} else if (msg.what == TO_LOGIN) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(Login.class);
			}
		}
	};

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.hindAllBtn();
		topBar.setTitle("上传附件照片");
	}

	private class PicAdpter extends BaseAdapter {
		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public PicAdpter(Context context) {
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return uploadFileInfos.size();
		}

		@Override
		public UpdateFileInfo getItem(int position) {
			return uploadFileInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			UpdateFileInfo fileInfo = uploadFileInfos.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.list_item_iv_tv_upload, null);
				holder = new ViewHolder();
				holder.item_icon = (ImageView) convertView.findViewById(R.id.item_icon);
				holder.size_tv = (TextView) convertView.findViewById(R.id.item_tv_size);
				holder.progress = (BuProgress) convertView.findViewById(R.id.up_load_progress);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.item_icon.setImageBitmap(fileInfo.bitmap);
			holder.progress.setProgress(fileInfo.progress);
			holder.size_tv.setText(fileInfo.fileSize);
			return convertView;
		}

		class ViewHolder {
			ImageView item_icon;// 数量
			TextView size_tv;// 昵称
			BuProgress progress;// 昵称
		}

	}

	private class HttpMultipartPost extends AsyncTask<Integer, Integer, String> {

		private long totalSize = 0;

		@Override
		protected void onPreExecute() {
		}

		/**
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 * @arg0 index
		 */
		@Override
		protected String doInBackground(Integer... args) {

			final int index = args[0];
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext httpContext = new BasicHttpContext();
			HttpPost httpPost = new HttpPost(upload_url);

			try {
				CustomMultipartEntity multipartContent = new CustomMultipartEntity(new ProgressListener() {
					@Override
					public void transferred(long num) {
						publishProgress(index, (int) ((num / (float) totalSize) * 100));
					}
				});

				FormBodyPart fromBodyPart = new FormBodyPart("file", new FileBody(new File(FileHloder.DIR_PIC + fileNames.get(index))));
				multipartContent.addPart(fromBodyPart);

				multipartContent.addPart("ticket", new StringBody(ticket));
				multipartContent.addPart("hidden_danger_id", new StringBody(danger_id));
				multipartContent.addPart("file_name", new StringBody(fileNames.get(index)));

				totalSize = multipartContent.getContentLength();
				httpPost.setEntity(multipartContent);
				HttpResponse response = httpClient.execute(httpPost, httpContext);
				String serverResponse = EntityUtils.toString(response.getEntity());
				return serverResponse;

			} catch (Exception e) {
				System.out.println(e);
			}
			return null;

		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			int index = progress[0];
			int prgs = progress[1];
			uploadFileInfos.get(index).progress = prgs;
			Message msg = handler.obtainMessage();
			msg.what = UPDATE_PROGRESS;
			msg.arg1 = index;
			msg.sendToTarget();
			if (prgs >= 100) {
				Message over_msg = handler.obtainMessage();
				over_msg.what = DOWNLOAD_COMPLETE;
				over_msg.arg1 = index;
				over_msg.sendToTarget();

				Message finalUpdate = handler.obtainMessage();
				finalUpdate.what = UPDATE_PROGRESS;
				handler.sendMessageDelayed(finalUpdate, UPDATE_GAP + 100);
			}
		}

		@Override
		protected void onPostExecute(String ti) {
			Log.d("RESULT_TAG", ti + "");
		}
	}

	class UpdateFileInfo {
		Bitmap bitmap;
		String fileSize;
		int progress = 0;

		public UpdateFileInfo(Bitmap bitmap, String fileSize) {
			this.bitmap = bitmap;
			this.fileSize = fileSize;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 在欢迎界面屏蔽BACK键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return false;
	}

}